package com.employee.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录验证过滤器
 * 拦截所有请求，验证用户是否已登录
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    
    // 不需要登录验证的URL
    private static final String[] EXCLUDE_URLS = {
        "/login.html",
        "/login",
        "/css/",
        "/js/",
        "/images/",
        "/pages/"  // 允许访问页面，但操作需要登录
    };
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) 
            throws IOException, ServletException {
        
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        
        // 获取请求URI
        String uri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String path = uri.substring(contextPath.length());
        
        // 检查是否是排除的URL
        if (isExcludedUrl(path)) {
            filterChain.doFilter(request, response);
            return;
        }
        
        // 检查Session中是否有用户信息
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute("username") != null) {
            // 已登录，放行
            filterChain.doFilter(request, response);
        } else {
            // 未登录，判断是否是AJAX请求
            String requestType = request.getHeader("X-Requested-With");
            if ("XMLHttpRequest".equals(requestType)) {
                // AJAX请求，返回JSON
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("{\"code\":401,\"message\":\"未登录或登录已过期\"}");
            } else {
                // 普通请求，重定向到登录页
                response.sendRedirect(contextPath + "/login.html");
            }
        }
    }
    
    @Override
    public void destroy() {
    }
    
    /**
     * 检查URL是否在排除列表中
     */
    private boolean isExcludedUrl(String path) {
        for (String excludeUrl : EXCLUDE_URLS) {
            if (path.startsWith(excludeUrl) || path.equals("/") || path.isEmpty()) {
                return true;
            }
        }
        return false;
    }
}
